package ro.thich.alchemy;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;

public class ElementActivity extends ListActivity
 {

	// DAO
	private ElementDAO dao;
	private MenuItem del;
	private Bundle b;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Create DAO object
		dao = new ElementDAO(this);
		// Set the list adapter and get TODOs list via DAO
		setListAdapter(new ListAdapter(this, dao.getTodos()));
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Element todo = (Element)getListAdapter().getItem(position);
		if(del.isChecked()){
			// TODO item that was clicked
			// Delete TODO object from the database
			dao.deleteTodo(todo.getId());
			// Set the list adapter and get TODOs list via DAO
			setListAdapter(new ListAdapter(this, dao.getTodos()));
			// Display success information
			Toast.makeText(getApplicationContext(), "Deleted!", Toast.LENGTH_LONG).show();
		}
		else {
			b = getIntent().getExtras();
			if (b == null) {
				Toast.makeText(getApplicationContext(), "Eroare bundle!", Toast.LENGTH_SHORT).show();
			}
			Intent intent = new Intent(this, MainActivity.class);
			// Start activity
			intent.putExtra(b.getString("btn"), todo.getText());
			startActivity(intent);
			// Finish this activity
			this.finish();
		}

	}

	/* ************************************************************* *
	 * Menu service methods
	 * ************************************************************* */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.element, menu);
		del = menu.findItem(R.id.del);
		del.setChecked(false);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Since we have only ONE option this code is not complicated :)
		switch(item.getItemId()){
			case R.id.menu:
		
				// Create an intent
				Intent intent = new Intent(this, AddElement.class);
				// Start activity
				startActivity(intent);
				// Finish this activity
				this.finish();
				// Close the database
				dao.close();
				break;
			case R.id.del:
				if(del.isChecked()){
					del.setChecked(false);
				}
				else {
					del.setChecked(true);
				}
				break;
		}
		return super.onOptionsItemSelected(item);
	}
}
